from flask import Flask, render_template, request, redirect

app = Flask(__name__)
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, LoginManager, login_user, logout_user, login_required #导入flask——login相关包
import requests

app = Flask(__name__)
app.config['SECRET_KEY'] = 'image'

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/image' #链接数据库

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
import base64 #导入base64包

#构造数据库用户表模型
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_name = db.Column(db.String(20))
    password = db.Column(db.String(20))

# 在第一次运行时，将数据库创建
with app.app_context():
    db.create_all()

# 记录日志
def log_request(req: "flask request", res: str):
    print(req.form)
    print(req.host_url)
    print(req.remote_addr)
    with open("log.log", "a") as log:
        print(req.form, req.host_url, req.remote_addr, req.headers.get('User-Agent'), file=log, sep="|")


# 访问受保护接口时，先校验权限
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)


#
@app.route("/", methods=["GET"])
@login_required
def index():
    return render_template("index.html", title="首页")


@app.route("/plant", methods=["GET", "POST"])
@login_required
def plant():
    if request.method == "POST":
        # 接受前端发来的图片
        file = request.files.get("file")
        # 读取图片
        info = file.read()
        # 发送请求获取access——token
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=29BYGXAMr2zr8mSjwpHG1uXQ&client_secret=V0RNsIH3izF7wAMNIvvQ7Fnei08YBsw0'
        response = requests.get(host)

        if response:
            access_token = response.json()['access_token']
            request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant"
            # base64加码

            img = base64.b64encode(info)
            #构建请求请求识别接口
            params = {"image": img, "baike_num": 10}
            request_url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            response = requests.post(request_url, data=params, headers=headers)
            if response:
                # 获取第一个结果
                result = response.json()["result"][0]
                print(result)

                return render_template("plant_result.html", title="植物识别", data=result)
    return render_template('plant.html', title="植物识别")
# 同请求植物
@app.route("/animal", methods=["GET", "POST"])
@login_required
def animal():
    if request.method == "POST":
        file = request.files.get("file")
        info = file.read()
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=29BYGXAMr2zr8mSjwpHG1uXQ&client_secret=V0RNsIH3izF7wAMNIvvQ7Fnei08YBsw0'
        response = requests.get(host)

        if response:
            access_token = response.json()['access_token']
            request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"

            img = base64.b64encode(info)
            #
            params = {"image": img, "baike_num": 10}
            request_url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/x-www-form-urlencoded'}
            response = requests.post(request_url, data=params, headers=headers)
            if response:
                result = response.json()["result"][0]
                print(result)

                return render_template("animal_result.html", title="动物识别", data=result)
    return render_template('animal.html', title="动物识别")


@app.route('/signup', methods=['GET', "POST"])
def register():
    if request.method == "POST":
        # 获取前端发送的所有参数
        user_name = request.form.get("username")
        password = request.form.get("password")
        password2 = request.form.get("password2")
        # 校验参数是否为空
        if user_name is None:
            return render_template("signup.html", msg="用户名不能为空")
        elif password is None:
            return render_template("signup.html", msg="密码不能为空")
        elif password != password2:
            return render_template("signup.html", msg="两次密码不一致")
        user = User.query.filter(User.user_name == user_name).first()
        # 校验该用户是否已经注册
        if user is not None:
            return render_template("signup.html", msg="该用户已经注册了")

        user = User(user_name=user_name, password=password)
        db.session.add(user)
        db.session.commit()
        return redirect("/login")
    return render_template('signup.html')


@app.route('/login', methods=['GET', "POST"])
def login():
    if request.method == "POST":
        # 获取前端发送的所有参数

        username = request.form.get("username")
        password = request.form.get("password")
        user = User.query.filter(User.user_name == username).first()
        # 判断用户状态

        if user is None:
            msg = "用户不存在"
            return render_template("login.html", msg=msg)
        elif user.password != password:
            msg = "错误密码"
            return render_template("login.html", msg=msg)
        else:
            log_request(request, user)

            login_user(user, remember=True)

            return redirect("/")
    return render_template('login.html')

# 登出
@app.route("/logout", methods=["GET"])
def logout():
    logout_user()
    return redirect("/")


#
@app.route("/log", methods=["post",'get'])
def log():
    data=[]
    # 读取日志文件，按行读取
    with open("log.log","r") as f:
        info_list=f.readlines()
        for i in info_list:
            # 根据｜切割，然后存入data中
            data.append(i.split("|"))

    return render_template('log.html',data=data)


if __name__ == '__main__':
    app.run()
